Security News
pnpm 10.0.0 Blocks Lifecycle Scripts by Default
pnpm 10 blocks lifecycle scripts by default to improve security, addressing supply chain attack risks but sparking debate over compatibility and workflow changes.
The 'oas' npm package is a tool for working with OpenAPI Specifications (OAS). It provides utilities for validating, bundling, and transforming OpenAPI documents, making it easier to work with API specifications in a programmatic way.
Validation
This feature allows you to validate an OpenAPI Specification to ensure it adheres to the OpenAPI standards. The code sample demonstrates how to load an OpenAPI spec from a file and validate it using the 'oas' package.
const OAS = require('oas');
const spec = require('./path/to/openapi/spec.json');
OAS.validate(spec).then(() => {
console.log('Specification is valid');
}).catch((err) => {
console.error('Specification is invalid', err);
});
Bundling
This feature allows you to bundle multiple OpenAPI files into a single file. The code sample demonstrates how to load an OpenAPI spec and bundle it using the 'oas' package.
const OAS = require('oas');
const spec = require('./path/to/openapi/spec.json');
OAS.bundle(spec).then((bundledSpec) => {
console.log('Bundled Specification:', bundledSpec);
}).catch((err) => {
console.error('Error bundling specification', err);
});
Transformation
This feature allows you to transform an OpenAPI Specification to a different version or format. The code sample demonstrates how to load an OpenAPI spec and transform it to version 3.0.0 using the 'oas' package.
const OAS = require('oas');
const spec = require('./path/to/openapi/spec.json');
OAS.transform(spec, { version: '3.0.0' }).then((transformedSpec) => {
console.log('Transformed Specification:', transformedSpec);
}).catch((err) => {
console.error('Error transforming specification', err);
});
Swagger Parser is a powerful tool for validating, parsing, and dereferencing Swagger and OpenAPI documents. It offers similar functionalities to 'oas' but is more focused on parsing and dereferencing, making it a good choice for applications that need to work with complex API specifications.
OpenAPI Generator is a comprehensive tool for generating API client libraries, server stubs, and API documentation from OpenAPI Specifications. While 'oas' focuses on validation and transformation, OpenAPI Generator excels in code generation, making it suitable for developers looking to automate the creation of API clients and servers.
Swagger JSDoc is a library that allows you to generate OpenAPI documentation from JSDoc comments in your code. It is particularly useful for projects that want to maintain API documentation alongside the codebase. Unlike 'oas', which focuses on working with existing OpenAPI specs, Swagger JSDoc helps in creating them from code annotations.
Comprehensive tooling for working with OpenAPI definitions
oas
is the library that we've built at ReadMe for powering everything we do related to OpenAPI; from our Reference Guides, to our Metrics product or to other in-house tooling like code generation, request execution, and SDK code generation.
npm install oas
Note If you need to use this library within a browser you'll likely need to use a bundler like Webpack or Rollup.
oas
offers a main Oas
class, which will be your main entrypoint for using the library.
import Oas from 'oas';
import petstoreSpec from '@readme/oas-examples/3.0/json/petstore.json';
const petstore = new Oas(petstoreSpec);
Here the Oas
constructor takes a JSON API definition (petstoreSpec
). All API definitions you feed it must be JSON and must be an OpenAPI definition. If you have a YAML or Swagger definition you will need to convert it (our oas-normalize library can do this for you). And if you're in a CJS or non-import
environment you can pull the library in with require('oas').default
.
From here, the following APIs are at your disposal.
Because this library has full TypeScript types and docblocks this README is not intended to be full documentation so consult the individual method docblocks if you need more information on a specific method.
Method | Description |
---|---|
#dereference() | Dereference the current OpenAPI definition. Note that this will ignore circular references. |
#getCircularReferences() | Retrieve an array of any circular $ref pointer that may exist wthin the OpenAPI definition. Note that this requires #dereference() to be called first. |
#getDefinition() | Retrieve the OpenAPI definition that was fed into the Oas constructor. |
#getTags() | Retrieve an array of all tags that exist within the API definition and are set on operations. |
#getPaths() | Retrieve every operation that exists within the API definition. This returns an array of instances of the Operation class. |
#getVersion() | Retrieve the OpenAPI version that this API definition is targeted for. |
#getWebhooks() | Retrieve every webhook operation that exists within the API definition. This returns an array of instances of the Webhook class. |
#init() | An alternative for new Oas() that you can use if the typing on the Oas constructor gives you trouble. Typing OpenAPI definitions is hard! |
Method | Description |
---|---|
#findOperation() | Discover an operation with the current OpenAPI definition that matches a given URL and HTTP method. |
#findOperationWithoutMethod() | Like oas.findOperation() but without supplying an HTTP method. |
#getOperation() | Same as oas.findOperation() but this returns an instance of the Operation class. |
#operation() | Retrieve an instance of the Operation or Webhook classes for a given path and HTTP method. |
Method | Description |
---|---|
#defaultVariables() | Retrieve the default server variables for a specific server URL, while also potentially factoring in user data. You can specify user variable data to the Oas constructor. Check out Using Variables in Documentation for some background on how we use this. |
#replaceUrl() | Replace a given templated server URL with supplied server variable data. |
#splitUrl() | Chunk out a specific server URL into its individual parts. |
#splitVariables | Chunk out a given URL and if it matches a server URL in the OpenAPI file, extract the matched server variables that are present in the URL. |
#url() | Retrive a fully composed server URL. You can optionally select which of the defined server URLs to use as well as specify server variable information. |
#variables() | Retrieve all server variables that a specific server URL in the definition has. |
Method | Description |
---|---|
#getExtension() | Retrieve a given specification extension if it exists at the root of the API definition. |
#hasExtension() | Determine if a given specification extension exists on the root of the API definition. |
Method | Description |
---|---|
#getAuth() | Retrieve the appropriate API keys for the current OpenAPI definition from an object of user data. Check out Using Variables in Documentation for some background on how we use this. |
For your convenience, the entrypoint into the Operation
class should generally always be through Oas.operation()
. For example:
import Oas from 'oas';
import petstoreSpec from '@readme/oas-examples/3.0/json/petstore.json';
const petstore = new Oas(petstoreSpec);
const operation = petstore.operation('/pet', 'post');
Method | Description |
---|---|
#getContentType() | Retrieve the primary request body content type. If multiple are present, prefer whichever is JSON-compliant. |
#getDescription() | Retrieve the description that's set on this operation. This supports common descriptions that may be set at the path item level. |
#getOperationId() | Retrieve the operationId that's present on the operation, and if one is not present one will be created based off the method + path and returned instead. |
#hasOperationId() | Determine if the operation has an operationId present. |
#isDeprecated() | Determine if this operation is marked as deprecated. |
#isFormUrlEncoded() | Determine if this operation requires its payload to be delivered as application/x-www-form-urlencoded . |
#isJson() | Determine if this operation requires its payload to be delivered as JSON. |
#isMultipart() | Determine if this operation requires its data to be sent as a multipart payload. |
#isXml() | Determine if this operation requires its data to be sent as XML. |
#getHeaders() | Retrieve all headers that can either be sent for or returned from this operation. This includes header-based authentication schemes, common header parameters, and request body and response content types. |
#getSummary() | Retrieve the summary that's set on this operation. This supports common summaries that may be set at the path item level. |
#getTags() | Retrieve all tags, and their metadata, that exist on this operation. |
Method | Description |
---|---|
#getCallback() | Retrieve a specific callback on this operation. This will return an instance of the Callback class. |
#getCallbackExamples() | Retrieve an array of all calback examples that this operation has defined. |
#getCallbacks() | Retrieve all callbacks that this operation has. Similar to Oas.getPaths() returning an array of Operation instances this will return an array of Callback instances. |
#hasCallbacks() | Determine if this operation has any callbacks defined. |
Note All parameter accessors here support, and will automatically retrieve and handle, common parameters that may be set at the path item level.
Method | Description |
---|---|
#getParameters() | Retrieve all parameters that may be used with on this operation. |
#getParametersAsJSONSchema() | Retrieve and convert the operations parameters into an array of JSON Schema schemas for each available type of parameter available on the operation: path , query , body , cookie , formData , and header . |
#hasParameters() | Determine if the operation has any parameters to send. |
#hasRequiredParameters() | Determine if any of the parameters on this operation are required. |
Method | Description |
---|---|
#getRequestBody() | Retrieve the raw request body object for a given content type. If none is specified it will return either the first that's JSON-like, or the first defined. |
#getRequestBodyExamples() | Retrieve an array of all request body examples that this operation has defined. |
#getRequestBodyMediaTypes() | Retrieve a list of all the media/content types that the operation can accept a request body payload for. |
#hasRequestBody() | Determine if this operation has a request body defined. |
Method | Description |
---|---|
#getResponseAsJSONSchema() | Retrive and convert a response on this operation into JSON Schema. |
#getResponseByStatusCode() | Retrieve the raw response object for a given status code. |
#getResponseExamples() | Retrieve an array of all response examples that this operation has defined. |
#getResponseStatusCodes() | Retrieve all status codes that this operation may respond with. |
#hasRequiredRequestBody() | Determine if this operation has a required request body. |
Method | Description |
---|---|
#getSecurity() | Return all security requirements that are applicable for either this operation, or if the operation has none specific to it, then for the entire API. |
#getSecurityWithTypes() | Return a collection of all security schemes applicable to this operation (using #getSecurity() ), grouped by how the security should be handled (either AND or OR auth requirements). |
#prepareSecurity | Return an object of every security scheme that can be used on this operation, indexed by the type of security scheme it is (eg. Basic , OAuth2 , APIKey , etc.). |
Method | Description |
---|---|
#getExtension() | Retrieve a given specification extension if it exists on this operation. |
#hasExtension() | Determine if a given specification extension exists on this operation. |
The Callback
class inherits Operation
so every API available on instances of Operation
is available here too. Much like Operation
, we also support common parameters, summaries, and descriptions that may be set at the path item level within a callbacks
definition.
Method | Description |
---|---|
#getIdentifier() | Retrieve the primary identifier of this callback. |
Because our Webhook
class extends Operation
, every API that's available on the Operation class is available on webhooks.
Though oas
used to offer functionality related to this, it does no longer. If you need an OpenAPI (or Swagger) definition for your API we recommend checking out the API editing experience within ReadMe, manually maintaining JSON/YAML files (it sounds worse than it actually is), or the language-agnostic swagger-inline.
FAQs
Comprehensive tooling for working with OpenAPI definitions
The npm package oas receives a total of 123,948 weekly downloads. As such, oas popularity was classified as popular.
We found that oas demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
pnpm 10 blocks lifecycle scripts by default to improve security, addressing supply chain attack risks but sparking debate over compatibility and workflow changes.
Product
Socket now supports uv.lock files to ensure consistent, secure dependency resolution for Python projects and enhance supply chain security.
Research
Security News
Socket researchers have discovered multiple malicious npm packages targeting Solana private keys, abusing Gmail to exfiltrate the data and drain Solana wallets.